package com.clss.emergencycall.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.amap.api.maps.model.LatLng;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.clss.emergencycall.base.BaseActivity;
import com.clss.emergencycall.base.Constant;
import com.clss.emergencycall.R;
import com.clss.emergencycall.bean.ReciveMessageEntity;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.bumptech.glide.load.resource.bitmap.VideoDecoder.FRAME_OPTION;

/**
 * 一般工具类
 * Created by harisucici on 2017/6/13.
 */

public class Tools {
    private static final String TAG = "Tools";

    private static int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    /**
     * 两次点击按钮之间的点击间隔不能少于1000毫秒
     *
     * @return
     */
    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    public static String encode(String s) {
        String result = "";
        try {
            result = URLEncoder.encode(s, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String getNowTime() {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH:mm");
//        java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat("HH:mm");
        return formater.format(new Date());
    }

    public static String getNowTimeToRecord() {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        return formater.format(new Date());
    }

    public static String timeToDate(long time) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formater.format(time);
    }

    public static String timeToDate(String time) {
        SimpleDateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formater.format(Long.parseLong(time));
    }

    public static String dateToTime(String date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        String time = "";
        try {
            Date d = dateFormat.parse(date);
            time = timeFormat.format(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    public static String getStampToTime(long stamp) {
        SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
        timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return timeFormat.format(new Date(stamp));
    }

    /**
     * 格式化时间（输出类似于 刚刚, 4分钟前, 一小时前, 昨天这样的时间）
     *
     * @param time 需要格式化的时间 如"2014-07-14 19:01:45"
     * @return time为null，或者时间格式不匹配，输出空字符""
     */
    public static String formatDisplayTime(long time) {
        String display = "";
        int tMin = 60 * 1000;
        int tHour = 60 * tMin;
        int tDay = 24 * tHour;

        if (time != 0) {
            String pattern = "yyyy-MM-dd HH:mm:ss";
            try {
                Date tDate = new SimpleDateFormat(pattern).parse(timeToDate(time));
                Date today = new Date();
                SimpleDateFormat thisYearDf = new SimpleDateFormat("yyyy");
                SimpleDateFormat todayDf = new SimpleDateFormat("yyyy-MM-dd");
                Date thisYear = new Date(thisYearDf.parse(thisYearDf.format(today)).getTime());
                Date yesterday = new Date(todayDf.parse(todayDf.format(today)).getTime());
                Date beforeYes = new Date(yesterday.getTime() - tDay);
                if (tDate != null) {
                    @SuppressWarnings("unused")
                    SimpleDateFormat halfDf = new SimpleDateFormat("MM月dd日");
                    long dTime = today.getTime() - tDate.getTime();
                    if (tDate.before(thisYear)) {
                        display = new SimpleDateFormat("yyyy年MM月dd日").format(tDate);
                    } else {
                        if (dTime < tMin) {
                            display = "刚刚";
                        } else if (dTime < tHour) {
                            display = (int) Math.ceil(dTime / tMin) + "分钟前";
                        } else if (dTime < tDay && tDate.after(yesterday)) {
                            display = (int) Math.ceil(dTime / tHour) + "小时前";
                        } else if (tDate.after(beforeYes) && tDate.before(yesterday)) {
                            display = "昨天  " + new SimpleDateFormat("HH:mm").format(tDate);
                        } else {
                            display = timeToDate(tDate.getTime());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return display;
    }

    /**
     * 秒转化为天小时分秒字符串
     *
     * @param minute
     * @return String
     */
    public static String formatMinute(String minute) {
        long min = Long.parseLong(minute);
        String timeStr = min + "分钟";
        if (min >= 60) {
            long mins = min % 60;
            long hour = min / 60;
            if (mins != 0) {
                timeStr = hour + "小时" + mins + "分钟";
            } else {
                timeStr = hour + "小时";
            }
            if (hour > 24) {
                hour = (min / 60) % 24;
                long day = ((min / 60) / 24);
                if (mins != 0) {
                    timeStr = day + "天" + hour + "小时" + mins + "分钟";
                } else {
                    timeStr = day + "天" + hour + "小时";
                }
            }
        }
        return timeStr;
    }

    /**
     * 打开扬声器
     */
    public static void openSpeaker(Context context) {
        String m = Build.MANUFACTURER;
        try {
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (!m.toLowerCase().contains("xiaomi")) {
                if (audioManager != null) {
                    audioManager.setMode(AudioManager.ROUTE_SPEAKER);
                }
            }
            if (audioManager != null && !audioManager.isSpeakerphoneOn()) {
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                audioManager.setSpeakerphoneOn(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭扬声器
     */
    public static void closeSpeaker(Context context) {
        try {
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (audioManager != null) {
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
                if (audioManager.isSpeakerphoneOn()) {
                    audioManager.setSpeakerphoneOn(false);
                    audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 0,
                            AudioManager.STREAM_VOICE_CALL);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 麦克风静音
     */
    public static void closeListener(Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            audioManager.setMicrophoneMute(true);
        }
    }

    public static void openListener(Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            audioManager.setMicrophoneMute(false);
        }
    }

    /**
     * 完全静音
     * 可取为 STREAM_VOICE_CALL（通话）
     * 、STREAM_SYSTEM（系统声音）
     * 、STREAM_RING（铃声）
     * 、STREAM_MUSIC（音乐）
     * 、STREAM_ALARM（闹铃声）
     */
    public static void closeAllSound(Context context, boolean b) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            setMaxOrMinVolume(audioManager, AudioManager.STREAM_VOICE_CALL, b);
            //ringerMode为手机的系统声音设置的状态值，0位静音，1为震动，2为响铃
            final int ringerMode = audioManager.getRingerMode();
            if(ringerMode !=0) {
                setMaxOrMinVolume(audioManager, AudioManager.STREAM_SYSTEM, b);
                setMaxOrMinVolume(audioManager, AudioManager.STREAM_RING, b);
            }
            setMaxOrMinVolume(audioManager, AudioManager.STREAM_MUSIC, b);
            setMaxOrMinVolume(audioManager, AudioManager.STREAM_ALARM, b);
            /** 这两个需要去设置页更改权限 */
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                Settings.System.putInt(context.getContentResolver(), Settings.System.VIBRATE_WHEN_RINGING, b ? 1 : 0);
//            }
            /** 静音模式和普通模式  暂时注释掉*/
//            audioManager.setRingerMode(b ? AudioManager.RINGER_MODE_NORMAL : AudioManager.RINGER_MODE_SILENT);
        }
    }

    /***
     *  设置某个streamType的音量。
     * @param audioManager
     * @param streamtype
     * @param b 开关
     */
    private static void setMaxOrMinVolume(AudioManager audioManager, int streamtype, boolean b) {
        int max = audioManager.getStreamMaxVolume(streamtype);
        Lg.i(TAG, "setMaxOrMinVolume: " + max);
        audioManager.setStreamVolume(streamtype, b ? max : max / 5, 0);
    }

    /**
     * 备用的开关静音模式
     */
    public static void silentSwitchOn(Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            audioManager.getStreamVolume(AudioManager.STREAM_RING);
            Lg.d("Silent:", "RINGING 已被静音");
        }
    }

    public static void silentSwitchOff(Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        if (audioManager != null) {
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            audioManager.getStreamVolume(AudioManager.STREAM_RING);
            Lg.d("SilentListenerService", "RINGING 取消静音");
        }
    }


    /*
     * base64 互转
     */
    public static Bitmap Base642Bitmap(String s) {
        byte[] bytes = Base64.decode(s, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    public static String Bitmap2Base64(Bitmap bit) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bit.compress(Bitmap.CompressFormat.PNG, 80, bos);//参数100表示不压缩
        byte[] bytes = bos.toByteArray();
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

    /**
     * 图片加载工具Glide加入token
     */
    public static void showUrlImage(Context context, String url, ImageView imageView) {
        LazyHeaders headers = new LazyHeaders
                .Builder()
                .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                .build();
        GlideUrl glideUrl = new GlideUrl(url, headers);
        Glide.with(context)
                .load(glideUrl)
                .into(imageView);
    }

    /**
     * 图片加载工具Glide加入token
     */
    public static void showUrlImage(Context context, String url, ImageView imageView, int placeholder) {
        LazyHeaders headers = new LazyHeaders
                .Builder()
                .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                .build();
        GlideUrl glideUrl = new GlideUrl(url, headers);
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(placeholder);
        requestOptions.error(placeholder);
        Glide.with(context)
                .setDefaultRequestOptions(requestOptions)
                .load(glideUrl)
                .into(imageView);
    }

    /**
     * 图片加载工具Glide 加载全路径url
     */
    public static void showAllUrl(Context context, String url, ImageView imageView, int placeholder) {
        GlideUrl glideUrl = new GlideUrl(url);
        RequestOptions requestOptions = new RequestOptions();
        requestOptions.placeholder(placeholder);
        requestOptions.error(placeholder);
        Glide.with(context)
                .setDefaultRequestOptions(requestOptions)
                .load(glideUrl)
                .into(imageView);
    }


    /**
     * 图片加载工具Glide加入token
     */
    public static void showUrlImage(Fragment fragment, String url, final ImageView imageView) {
        Glide.with(fragment)
                .load(new GlideUrl(url
                        , new LazyHeaders
                        .Builder()
                        .addHeader(Constant.APP_TOKEN, SpHelper.getInstance().getToken())
                        .build()))
//                .into(imageView);
                .into(new SimpleTarget<Drawable>() {
                    @Override
                    public void onResourceReady(Drawable resource, Transition<? super Drawable> transition) {
                        imageView.setImageDrawable(resource);
                    }
                });
    }

    public static void loadVideoScreenshot(final Context context, String uri, ImageView imageView) {
        RequestOptions requestOptions = RequestOptions.frameOf(100);
        requestOptions.set(FRAME_OPTION, MediaMetadataRetriever.OPTION_CLOSEST);
        requestOptions.transform(new BitmapTransformation() {
            @Override
            protected Bitmap transform(@NonNull BitmapPool pool, @NonNull Bitmap toTransform, int outWidth, int outHeight) {
                return toTransform;
            }
            @Override
            public void updateDiskCacheKey(MessageDigest messageDigest) {
                try {
                    messageDigest.update((context.getPackageName() + "RotateTransform").getBytes("utf-8"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        Glide.with(context).load(uri).apply(requestOptions).into(imageView);
    }

    /**
     * netType = 2 为移动网络
     * netType = 1 为WiFi网络
     * nteType = 0 为无网络
     *
     * @param context
     * @return
     */
    public static int getNetworkType(Context context) {
        int netType = 0;
        if (null == context){
            return netType;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return netType;
        }
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_MOBILE) {
            netType = 2;
        } else if (nType == ConnectivityManager.TYPE_WIFI) {
            netType = 1;
        }
        return netType;
    }

    /**
     * 获取屏幕的宽度px
     *
     * @param context 上下文
     * @return 屏幕宽px
     */
    public static int getScreenWidth(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();// 创建了一张白纸
        windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高
        return outMetrics.widthPixels;
    }

    /**
     * 获取屏幕的高度px
     *
     * @param context 上下文
     * @return 屏幕高px
     */
    public static int getScreenHeight(Context context) {
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();// 创建了一张白纸
        windowManager.getDefaultDisplay().getMetrics(outMetrics);// 给白纸设置宽高
        return outMetrics.heightPixels;
    }

    /**
     * dip转为PX
     */
    public static int dip2px(Context context, float dipValue) {
        float fontScale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * fontScale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取location中的具体地址
     *
     * @param locationString
     * @return
     */
    public static String getLocationAddress(String locationString) {
        int begin = locationString.indexOf("#address=") + 1;
        int end = locationString.indexOf("#country=");
        String address = "";
        if (begin > 0 && end > 0) {
            address = locationString.substring(begin + 8, end);
        }
        return address;
    }

    /**
     * 获取location中的省
     *
     * @param locationString
     * @return
     */
    public static String getLocationProvince(String locationString) {
        int begin = locationString.indexOf("#province=") + 1;
        int end = locationString.indexOf("#city=");
        String province = "";
        if (begin > 0 && end > 0) {
            province = locationString.substring(begin + 9, end);
        }
        return province;
    }

    /**
     * 获取location中的市
     *
     * @param locationString
     * @return
     */
    public static String getLocationCity(String locationString) {
        int begin = locationString.indexOf("#city=") + 1;
        int end = locationString.indexOf("#district=");
        String city = "";
        if (begin > 0 && end > 0) {
            city = locationString.substring(begin + 5, end);
        }
        return city;
    }

    /**
     * 获取location中的区
     *
     * @param locationString
     * @return
     */
    public static String getLocationDistrict(String locationString) {
        int begin = locationString.indexOf("#district=") + 1;
        int end = locationString.indexOf("#cityCode=");
        String district = "";
        if (begin > 0 && end > 0) {
            district = locationString.substring(begin + 9, end);
        }
        return district;
    }

    /**
     * 获取location中的adCode
     *
     * @param locationString
     * @return
     */
    public static String getLocationAdcode(String locationString) {
        int begin = locationString.indexOf("#adCode=") + 1;
        int end = locationString.indexOf("#address=");
        String adCode = "";
        if (begin > 0 && end > 0) {
            adCode = locationString.substring(begin + 7, end);
        }
        return adCode;
    }

    public static String getSite(String location, int position) {
        String[] strings = location.split("#");
        Lg.i(TAG, "getSite: " + strings);
        String s = strings[position];
        return s.substring(s.indexOf("=") + 1);
    }

    /**
     * 从38.024059,114.434081形式的坐标中取出内容
     *
     * @param latlng
     * @return
     */
    public static LatLng getLatLngFromString(String latlng) {
        String[] latlong = latlng.split(",");
        double latitude = Double.parseDouble(latlong[1]);
        double longitude = Double.parseDouble(latlong[0]);
        return new LatLng(latitude, longitude);
    }

    public static int checkFileType(String path) {
        if (path.contains(".mp4") || path.contains(".avi") || path.contains(".3gp")) {
            return Constant.TYPE_VIDEO;
        }
        if (path.contains(".mp3") || path.contains(".aac") || path.contains(".amr")) {
            return Constant.TYPE_VOICE;
        }
        if (path.contains(".png") || path.contains(".jpg")) {
            return Constant.TYPE_IMAGE;
        }
        return -1;
    }

    public static ReciveMessageEntity getReceiveMsgInfo(String text) {
        if (text.contains(Constant.SEND_IMAGE_MSG_TAG_START)) {
            return new ReciveMessageEntity(text
                    .replace(Constant.SEND_IMAGE_MSG_TAG_START, "")
                    .replace(Constant.SEND_IMAGE_MSG_TAG_END, "")
                    , Constant.TYPE_IMAGE);
        } else if (text.contains(Constant.SEND_VIDEO_MSG_TAG_START)) {
            return new ReciveMessageEntity(text
                    .replace(Constant.SEND_VIDEO_MSG_TAG_START, "")
                    .replace(Constant.SEND_VIDEO_MSG_TAG_END, "")
                    , Constant.TYPE_VIDEO);
        } else if (text.contains(Constant.SEND_VOICE_MSG_TAG_START)) {
            return new ReciveMessageEntity(text
                    .replace(Constant.SEND_VOICE_MSG_TAG_START, "")
                    .replace(Constant.SEND_VOICE_MSG_TAG_END, "")
                    , Constant.TYPE_VOICE);
        } else {
            return new ReciveMessageEntity("", -1);
        }
    }

    /**
     * 根据资源id拼接资源的下载地址
     */
//    public static String getIdToDownloadUrl(String id) {
//        return ApiConstants.getUploadFileUrl() + id;
//    }

    /**
     * 获取activity的view
     */
    public static View getContentView(Activity context) {
        return ((ViewGroup) context.findViewById(android.R.id.content)).getChildAt(0);
    }

    /**
     * 验证手机号码
     * 现有手机号段:
     * 移动：139   138   137   136   135   134   147   150   151   152   157   158    159   178  182   183   184   187   188
     * 联通：130   131   132   155   156   185   186   145   176
     * 电信：133   153   177   173   180   181   189
     * 虚拟运营商：
     * 170  171
     */
    public static boolean checkMobileNumber(String mobileNumber) {
        boolean flag = false;
        try {
            String n = "^((13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8})$";
            Pattern regex = Pattern.compile(n);
            Matcher matcher = regex.matcher(mobileNumber);
            flag = matcher.matches();
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    /**
     * 检查系统是否有downloadmanager
     *
     * @param context
     * @return
     */
    public static boolean canDownloadState(Context context) {
        try {
            int state = context.getPackageManager().getApplicationEnabledSetting("com.android.providers.downloads");
            if (state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER
                    || state == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED) {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 开启新的activity并传值
     *
     * @param fromActivity
     * @param toActivity
     */
    public static void startActivity(Activity fromActivity, Class<? extends BaseActivity> toActivity) {
        startActivity(fromActivity, toActivity, null);
    }

    public static void startActivity(Activity fromActivity, Class<? extends BaseActivity> toActivity,
                                     @Nullable Bundle bundle) {
        startActivity(fromActivity, toActivity, bundle, false);
    }

    public static void startActivity(Activity fromActivity, Class<? extends BaseActivity> toActivity,
                                     @Nullable Bundle bundle, boolean finishThisActivity) {
        Intent intent = new Intent(fromActivity, toActivity);
        if (null != bundle) {
            bundle.putString(Constant.ACTIVITY_NAME, fromActivity.getClass().getSimpleName());
            intent.putExtras(bundle);
        } else {
            Bundle b = new Bundle();
            b.putString(Constant.ACTIVITY_NAME, fromActivity.getClass().getSimpleName());
            intent.putExtras(b);
        }
        fromActivity.startActivity(intent);
        if (finishThisActivity) {
            fromActivity.finish();
        }
    }

    /**
     * 从通讯录选择联系人
     *
     * @param activity
     * @param uri
     * @return
     */
    public static String[] getPhoneContacts(Activity activity, Uri uri) {
        String[] contact = new String[2];
        ContentResolver cr = activity.getContentResolver();
        Cursor cursor = cr.query(uri, null, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();
            //取得联系人姓名
            int nameFieldColumnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            contact[0] = cursor.getString(nameFieldColumnIndex);
            //取得电话号码
            String ContactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            Cursor phone = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + ContactId, null, null);
            if (phone != null) {
                phone.moveToFirst();
                contact[1] = phone.getString(phone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            }
            phone.close();
            cursor.close();
        } else {
            return null;
        }
        return contact;
    }


    /****
     * 动态设置listview高度
     ****/
    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
    }

//    public static boolean isBadJson(String json) {
//        return !isGoodJson(json);
//    }
//
//    public static boolean isGoodJson(String json) {
//        if (StringUtils.isBlank(json)) {
//            return false;
//        }
//        try {
//            new JsonParser().parse(json);
//            return true;
//        } catch (JsonParseException e) {
//
//            return false;
//        }
//    }

    /**
     * 获取外网的IP(要访问Url，要放到后台线程里处理)
     *
     * @param @return
     * @return String
     * @throws
     * @Title: GetNetIp
     * @Description:
     */
    public static String getNetIp() {
        URL infoUrl = null;
        InputStream inStream = null;
        String ipLine = "";
        HttpURLConnection httpConnection = null;
        try {
//            infoUrl = new URL("http://ip168.com/");
            infoUrl = new URL("http://pv.sohu.com/cityjson?ie=utf-8");
            URLConnection connection = infoUrl.openConnection();
            httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inStream, "utf-8"));
                StringBuilder strber = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strber.append(line + "\n");
                }
                String n = "((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))";
                Pattern pattern = Pattern
                        .compile(n);
                Matcher matcher = pattern.matcher(strber.toString());
                if (matcher.find()) {
                    ipLine = matcher.group();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inStream.close();
                httpConnection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return ipLine;
    }


    public static boolean hasShortcut(Context context, String name) {
        String url;
        String packageName = "com.android.launcher3.settings";
        url = "content://" + packageName + ".settings/favorites?notify=true";
        try {
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = resolver.query(Uri.parse(url), new String[]{
                            "title", "iconResource"}, "title=?",
                    new String[]{name}, null);
            if (cursor != null && cursor.getCount() > 0) {
                return true;
            }
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static boolean hasShortcut1(Context context, String name) {
        String url;
        String packageName = "com.android.launcher3.settings";
        url = "content://" + packageName + ".settings/favorites?notify=true";
        try {
            ContentResolver resolver = context.getContentResolver();
            Cursor cursor = resolver.query(Uri.parse(url), new String[]{
                            "title"}, "title=?",
                    new String[]{name}, null);
            if (cursor != null && cursor.getCount() > 0) {
                cursor.close();
                return true;
            }
            cursor.close();
        } catch (Exception e) {
            if (e != null) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static int[] getViewCentreXY(View view) {
        int x, y;
        x = (int) (view.getX() + (view.getWidth() / 2));
        y = (int) (view.getY() + (view.getHeight() / 2));
        return new int[]{x, y};
    }

    public static boolean pingNetConnectionState(){
        Runtime runtime = Runtime.getRuntime();
        try{
            Process process = runtime.exec("/system/bin/ping -c 1 -w 300 www.baidu.com");
            int ret = process.waitFor();
            return ret == 0;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }
}
